import {afterEach, describe} from 'mocha'
import * as sinon from 'sinon'
import * as chai from 'chai'
import { runStep } from '../src/step'
// @ts-ignore
import fs from 'fs'
import * as step from '@flow-step/step-toolkit'

describe('set_multi_variable', () => {
  process.env.WORK_SPACE = 'test'
  const tempParamsFile = 'test/params';
  const tempStepContextFile = 'test/stepContext';
  let stubAppendFileSync: any
  let stubExportEnvVar: any
  let stubAddOuput: any

  beforeEach(() => {
    stubAppendFileSync = sinon.stub(fs, 'appendFileSync')
    stubExportEnvVar = sinon.stub(step, 'exportEnvVar')
    stubAddOuput = sinon.stub(step, 'addOutput')
  })

  afterEach(() => {
    sinon.restore()
    if (fs.existsSync(tempParamsFile)) {
      fs.unlinkSync(tempParamsFile);
    }
    if (fs.existsSync(tempStepContextFile)) {
      fs.unlinkSync(tempStepContextFile);
    }
  })

  it('should export the correct variables', async () => {
    process.env.variables = '[{"key":"a","value":"1"},{"key":"b","value":"2"}]'
    await runStep()

    sinon.assert.calledWith(stubExportEnvVar, "a", "1")
    sinon.assert.calledWith(stubExportEnvVar, "b", "2")
    sinon.assert.calledWith(stubAddOuput, "outputsToEnv.a=1")
    sinon.assert.calledWith(stubAddOuput, "outputsToEnv.b=2")

  })

  it('should eval the variables correctly', async () => {
    process.env.foo = 'bar'
    process.env.variables = '[{"key":"a","value":"${foo}"}]'
    await runStep()
    sinon.assert.calledWith(stubExportEnvVar, "a", "bar")
    sinon.assert.calledWith(stubAddOuput, "outputsToEnv.a=bar")
  })

  it('should fail if variable is invalid', async () => {
    process.env.foo = 'bar'
    process.env.variables = '[{"key":"a","value":"${foo"}]'
    chai.expect(await runStep()).to.equal(-1)
  })
})